﻿/*
   Copyright 2012 University of Southampton

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Linq;
using uk.ac.soton.ses.DAL;
using System.Data;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;

namespace uk.ac.soton.ses.ExperimentDataFilesWebPart
{
    public partial class ExperimentDataFilesWebPartUserControl : UserControl
    {
        //Fields
        private int _experimentIDFilter = -1;

        //Properties
        //public int ExperimentIDFilter { get { return this._experimentIDFilter; } set { this._experimentIDFilter = value; } }

        public int SelectedRowID
        {
            get
            {
                if (this.ExperimentDataFilesGridView.SelectedIndex != -1 && this.ExperimentDataFilesGridView.Rows.Count>0 && this.ExperimentDataFilesGridView.SelectedIndex<this.ExperimentDataFilesGridView.Rows.Count)
                {
                    return (int)this.ExperimentDataFilesGridView.SelectedDataKey["ID"];
                    //ExperimentDataFile df= MaterialsMetadataOperations.GetExperimentDataFile((int)this.ExperimentDataFilesGridView.SelectedDataKey["ID"]);
                    //if (df != null)
                    //    return df.ID;
                    //else
                    //    return -1;
                }
                else
                {
                    return -1;
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            DebugMessageFile("Usercontrol>Page_load");
            ExperimentDataFilesGridView.SelectedIndexChanged += new EventHandler(ExperimentDataFilesGridView_SelectedIndexChanged);
            this.ExperimentDataFilesGridView.RowDataBound += new GridViewRowEventHandler(ExperimentDataFilesGridView_RowDataBound);
            //this.DataBindDataFiles();
        }

        void ExperimentDataFilesGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            SPGridViewRow gvr = (SPGridViewRow)e.Row;
            if (e.Row.RowIndex >= 0)
            {
                ExperimentDataFile boundExperimentDataFile = e.Row.DataItem as ExperimentDataFile;
                if (boundExperimentDataFile != null)
                {
                    if (boundExperimentDataFile.IsDeleted == true)
                    {
                        gvr.CssClass = "DeletedItem";
                        //Label lblDeleted = (Label)gvr.FindControl("lbl_Deleted");
                        //lblDeleted.Text = "Deleted";
                        //Microsoft.SharePoint.WebControls.Menu control = ((Microsoft.SharePoint.WebControls.Menu)gvr.Cells[1].Controls[0]);
                        //control.TextCssClass += "DeletedItem";
                    }
                }
            }
        }

        void ExperimentDataFilesGridView_SelectedIndexChanged(object sender, EventArgs e)
        {
            DebugMessageFile("Usercontrol>selectedindexchanged");
            this.DataBindDataFiles();
            //this.OnSelectedRowChanged(this.SelectedRowData);
            //MaterialsMetadataEntities dbcontext = new MaterialsMetadataEntities();
            //int selectID = (int)ExperimentDataFilesGridView.SelectedDataKey["ID"];
            //ExperimentDataFile selectedDataFile = dbcontext.ExperimentDataFiles.First(df => df.ID == selectID);
        }

        public void DataBindWithoutFilter()
        {
            //To show all experiments, we just remove the filter by using -1 as the experiment ID
            this.DataBindToExperiment(-1);
        }
        public void DataBindToExperiment(int experimentID)
        {
            this._experimentIDFilter = experimentID;
            this.DataBindDataFiles();
        }

        private void DataBindDataFiles()
        {
            DebugMessageFile("Usercontrol>Databinding");

            //Data bind the grid view
            MaterialsMetadataContext dbcontext = HttpContext.Current.GetMaterialsDBContext();
            if (this._experimentIDFilter > 0)
            {
                this.ExperimentDataFilesGridView.DataSource = dbcontext.GetExperimentDataFilesByExperimentID(this._experimentIDFilter, false);
            }
            else
            {
                this.ExperimentDataFilesGridView.DataSource = dbcontext.ExperimentDataFiles;
            }
            this.ExperimentDataFilesGridView.DataBind();

            //Set the selected index to something sensible if it is larger than the number of rows
            if (this.ExperimentDataFilesGridView.SelectedIndex > this.ExperimentDataFilesGridView.Rows.Count - 1)
            {
                this.ExperimentDataFilesGridView.SelectedIndex = -1;
            }
        }

        private void DebugMessageFile(string s)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (FileStream fs = File.Open(@"c:\temp\debuglog.log", FileMode.Append, FileAccess.Write, FileShare.Read))
                    using (StreamWriter writer = new StreamWriter(fs))
                    {
                        writer.AutoFlush = true;
                        writer.WriteLine(s);
                        writer.Flush();
                        writer.Close();
                    }
                });
            }
            catch (Exception ex)
            {
                Label lbl = new Label();
                lbl.Text = ex.Message;
                this.Controls.Add(lbl);
            }
        }
    }
}
